#!/usr/bin/env python

import os, sys
from subprocess import call as _call
from shutil import copy, rmtree
from tempfile import mkdtemp
import atexit

def start_message(msg):
    sys.stdout.write("%s " % msg)
    sys.stdout.flush()

def end_message(msg):
    print msg
    sys.stdout.flush()

def call(cmd):
    return _call(cmd, shell=True)

tmpdir = mkdtemp()
atexit.register(lambda: rmtree(tmpdir))

call('svn export --force . "%s"' % tmpdir)
for svndir, destdir in [('home', os.path.expanduser('~'))]:
    if not os.path.exists(destdir):
        os.makedirs(destdir)
    svndir = os.path.join(tmpdir, svndir)
    for dirpath, dirnames, filenames in os.walk(svndir):
        try:
            dirnames.remove('.svn')
        except ValueError:
            pass
        destdirpath = destdir + dirpath[len(svndir):]
        for dirname in dirnames:
            path = os.path.join(destdirpath, dirname)
            if not os.path.exists(path):
                os.mkdir(path)
        for filename in filenames:
            origpath = os.path.join(dirpath, filename)
            destpath = os.path.join(destdirpath, filename)
            if os.path.exists(destpath):
                if open(origpath).read() != open(destpath).read():
                    call('diff -u "%s" "%s"' % (destpath, origpath))
                    answer = raw_input("Replace %s? " % destpath)
                    if answer.lower().startswith('y'):
                        copy(origpath, destpath)
            else:
                copy(origpath, destpath)


print "*** Please make sure ~/bin is in your $PATH ***"
print "*** Make sure your ~/.hongqnrc is up to date ***"
